//  Copyright © 2014 Allen County Public Library.

//        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.

package us.in.lib.acpl.Mobile_ACPL;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.api.rest.RestErrorHandler;
import org.springframework.web.client.RestClientException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import us.in.lib.acpl.Mobile_ACPL.models.BestSellerTitle;
import us.in.lib.acpl.Mobile_ACPL.models.OverdriveCheckoutsResponse;
import us.in.lib.acpl.Mobile_ACPL.models.OverdriveCheckoutsResponse.OverdriveCheckout;
import us.in.lib.acpl.Mobile_ACPL.models.OverdriveCheckoutsResponse.OverdriveCheckout.OverdriveCheckoutFormat;
import us.in.lib.acpl.Mobile_ACPL.models.OverdriveMetadata;
import us.in.lib.acpl.Mobile_ACPL.models.OverdrivePatronAuthRequest;
import us.in.lib.acpl.Mobile_ACPL.models.OverdrivePatronAuthResponse;
import us.in.lib.acpl.Mobile_ACPL.parents.BaseActivity;
import us.in.lib.acpl.Mobile_ACPL.rest.OverdriveAuthClient;
import us.in.lib.acpl.Mobile_ACPL.rest.OverdriveClient;
import us.in.lib.acpl.Mobile_ACPL.rest.OverdrivePatronClient;
import us.in.lib.acpl.Mobile_ACPL.models.OverdriveMetadata;


@EActivity(R.layout.overdrive)
public class OverdriveActivity extends BaseActivity{

    //ACPL: Removed Overdrive authorization header
	public final String AUTHORIZATION_HEADER = "";
	
	@ViewById
	ListView listView;
	
	@RestService
	OverdriveAuthClient authClient;
	
	@RestService
	OverdrivePatronClient patronClient;
	
	@RestService
	OverdriveClient metadataClient;
	
	OverdriveCheckoutsResponse checkouts;
	OverdriveCheckoutsAdapter adapter;
	
	HashMap<String,OverdriveMetadata> metadataDict;
	HashMap<String,Bitmap> coverDict;
	
	boolean resume;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}	
	
	@AfterViews
	public void afterViews(){
		this.getActionBar().setTitle("   Overdrive");
		authClient.setHeader("Authorization",  AUTHORIZATION_HEADER);
		authClient.setRestErrorHandler(new AuthErrorHandler());
		
		metadataDict = new HashMap<String,OverdriveMetadata>();
		coverDict = new HashMap<String,Bitmap>();
		adapter = new OverdriveCheckoutsAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				OverdriveCheckout checkout = checkouts.checkouts.get(position);
				OverdriveMetadata metadata = metadataDict.get(checkout.reserveId);
				
				Intent intent = new Intent(parent.getContext(),OverdriveDetailActivity_.class);
				intent.putExtra("title", metadata.title);
				intent.putExtra("author",metadata.creators.get(0).name);
				intent.putExtra("expires", checkout.expires);
				intent.putExtra("coverURL", metadata.images.cover.href);
				intent.putExtra("returnURL", checkout.actions.earlyReturn.href);
				
		
				
				for (OverdriveCheckoutFormat format : checkout.formats){
					if(format.formatType.equals("ebook-overdrive")){
						intent.putExtra("readURL", format.linkTemplates.downloadLink.href);
						break;
					}
				}
				
				startActivity(intent);
			
			}
			
		});
		
		getCheckouts();
		resume=true;
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if(resume){
			checkouts = null;
			adapter.notifyDataSetChanged();
			getCheckouts();	
		}

	}
	@Background
	public void getCheckouts(){
		
	//	request.grant_type="password";
		String username = this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE).getString("user", null);
		String password = this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE).getString("pin", null);
	//	request.username=username;
		//request.password=password;
		System.out.println(username);
		System.out.println(password);
	//	request.scope = "websiteid:287 authorizationname:allen";
		
		OverdrivePatronAuthRequest request = new OverdrivePatronAuthRequest("password",username,password,"websiteid:287 authorizationname:allen");
		
		OverdrivePatronAuthResponse response = authClient.authenticate(request);
		SharedPreferences prefs = this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString("overdriveToken", response.access_token);
		editor.commit();
		
		patronClient.setHeader("Authorization", "Bearer "+response.access_token);
		metadataClient.setHeader("Authorization", "Bearer "+response.access_token);
		OverdriveCheckoutsResponse checkouts = patronClient.getCheckouts();
		getCheckoutsComplete(checkouts);
		
	}
	
	@UiThread
	public void getCheckoutsComplete(OverdriveCheckoutsResponse checkouts){
		this.checkouts=checkouts;
		adapter.notifyDataSetChanged();
		


	}
	
	@Background
	public void getMetadata(String reserveId, String link){
		OverdriveMetadata metadata = metadataClient.getMetadata(link);
		getMetadataComplete(reserveId, metadata);
	}
	
	@UiThread
	public void getMetadataComplete(String reserveId, OverdriveMetadata metadata){
		metadataDict.put(reserveId, metadata);
		adapter.notifyDataSetChanged();
	}
	
	@Background
	public void getImage(String reserveId, String url){
		URL urlObj;
		Bitmap img;
		try {
			urlObj = new URL(url);
			img = BitmapFactory.decodeStream(urlObj.openConnection().getInputStream());
			getImageComplete(reserveId,img);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@UiThread
	public void getImageComplete(String reserveId, Bitmap image){
		coverDict.put(reserveId, image);
		adapter.notifyDataSetChanged();
	}
	
	
	public class OverdriveCheckoutsAdapter extends BaseAdapter{
	

		
		@Override
		public int getCount() {

			if(checkouts==null){
				return 1;
			}else{
				if(checkouts.checkouts!=null){
					return checkouts.checkouts.size();
				}else{
					return 0;
				}
			}
			
		}

		@Override
		public Object getItem(int position) {

			return checkouts.checkouts.get(position);
		}

		@Override
		public long getItemId(int position) {
	
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(checkouts==null){
				LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
				convertView = inflater.inflate(R.layout.overdrive_item, null);
				return convertView;
			}
			OverdriveCheckout title = checkouts.checkouts.get(position);
			LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
			convertView = inflater.inflate(R.layout.overdrive_item, null);
			
			
			OverdriveMetadata metadata = metadataDict.get(title.reserveId);
			
			if(metadata==null){
				getMetadata(title.reserveId,title.links.metadata.href);
			}else{
				TextView tv = (TextView)convertView.findViewById(R.id.searchResultLine1);
				tv.setText(metadata.title);
				
				tv = (TextView)convertView.findViewById(R.id.searchResultLine2);
				tv.setText(metadata.creators.get(0).name);
				
				Bitmap image = coverDict.get(title.reserveId);
				
				if(image==null){
					getImage(title.reserveId,metadata.images.thumbnail.href);
					convertView.findViewById(R.id.coverBar).setVisibility(View.VISIBLE);
				}else{
					ImageView iv = (ImageView)convertView.findViewById(R.id.smallCover);
					iv.setImageBitmap(image);
					convertView.findViewById(R.id.coverBar).setVisibility(View.INVISIBLE);
				}
			}
			
			
			return convertView;
		}
		
	}
	
	public class AuthErrorHandler implements RestErrorHandler{

		@Override
		public void onRestClientExceptionThrown(RestClientException e) {
			System.out.println(e.getLocalizedMessage());
			System.out.println(e.getMostSpecificCause());
		}
		
	}
	

}
